#include <QtGui>
#include <QPrintPreviewDialog>

#include "manager.h"
#include "inspectionswidget.h"
#include "dbworker.h"
#include "defs.h"

Manager *Manager::mAppManager = 0;

Manager::Manager() :
    mPacient (NULL),
    mMainWindow(NULL),
    mRentgenViewForm(NULL),
    mSettings (NULL),
    mIcons (new QMap<QString, QPixmap*>),
    dbw (new DBWorker(this))
{
    currentZipPath = QString();
}

Manager::~Manager()
{
    delete mMainWindow;
    delete mPacient;
    delete mRentgenViewForm;
    delete mSettings;
}

void Manager::setup()
{   // setting up all

    loadSettings();

    mMainWindow = new MainWindow();
    mMainWindow->setGeometry( 0, 0, winSize.width(), winSize.height() );
    mMainWindow->move(winPos);


    createPacient();
    mMainWindow->createConnectionsToPacient();

    connect( mMainWindow, SIGNAL(pacientOpened()), mMainWindow, SLOT(showPacientOnForm()) );
}

bool Manager::loadSettings()
{
    if (mSettings==NULL)
        mSettings = new QSettings(ORGANIZATION, APP_NAME, this);

    winSize = mSettings->value("WinSize", QSize(800, 600)).toSize();

    winPos = mSettings->value("WinTopLeft", QSize(100, 100)).toPoint();

    QString curFolder(mSettings->value("Folder", QString("")).toString());
    mCurrentFolder = curFolder;

    mOperationTypes.clear();

    mOperationTypes = mSettings->value("OperationTypes", FallOperationTypes).toStringList();
//    qDebug() << mOperationTypes;

    clearCurrentFolder();

    return true;
}

void Manager::saveSettings()
{
    LOG( "appManager", "Збереження налаштувань" );

    if (mSettings==NULL)
        mSettings = new QSettings(ORGANIZATION, APP_NAME, this);

    // saving parameters through QSettings
    // about MainWindow:
    mSettings->setValue("WinSize", mainWindow()->size());
    mSettings->setValue("WinTopLeft", mainWindow()->pos());
    mSettings->setValue("Folder", mCurrentFolder);

    mSettings->setValue("OperationTypes", mOperationTypes);

    clearCurrentFolder();
}

RentgenViewForm *Manager::rentgenViewForm()
{
    if (mRentgenViewForm==NULL)
    {
        mRentgenViewForm = new RentgenViewForm();
    }
    return mRentgenViewForm;
}

QString Manager::fileInCurrent(const QString &fileName) const
{
    return QDir::toNativeSeparators( curTempDir().absoluteFilePath(fileName) );
}

bool Manager::isIconLoaded(const QString& src)
{
    return mIcons->contains(src);
}

void Manager::loadIcon(const QString &src)
{
    qDebug() << "Loading icon row=" << "src=" << src;

    QPixmap *p = new QPixmap(App->fileInCurrent( src ));

    mIcons->insert(src, p);
}

QPixmap *Manager::iconAt(const QString& src)
{
    return mIcons->value(src);
}

void Manager::freeIcon(const QString &src)
{
    QMap<QString, QPixmap*>::iterator i = mIcons->find(src);
    qDebug() << "Freeing icon src=" << src;
    //    delete i.value();
    mIcons->erase(i);
}

void Manager::setCurrentFolder(const QString &path)
{
    mCurrentFolder = path;
}

QDir Manager::curTempDir() const
{
    const QString currentDirName = QString("current");
    QDir curDir (QDir::currentPath());

    QString path ( curDir.absoluteFilePath(currentDirName) );
    QDir current (path);
    if (!current.exists())
        curDir.mkdir(currentDirName);
    curDir.cd(currentDirName);
//    qDebug() << "IN Manager::curTempDir " << curDir;
    return curDir;
}

QString Manager::copyImage(const QString &path)
{
    if (path.isEmpty()) {
        return QString();
    }
    QFileInfo fi(path);
    QString newPhotoPath( App->curTempDir().absoluteFilePath(fi.fileName()) );
    QFileInfo fii (newPhotoPath);
    if (fii.exists())
    {
        LOG("copyImage", UkrString("Фото %1 уже є в папці %2")
            .arg(fii.fileName())
            .arg(curTempDir().path()));
        return fii.fileName();
    }
    QFile f(path);
    f.open(QIODevice::ReadOnly);
    if (!f.isOpen())
        return QString();
    bool res = f.copy( newPhotoPath );
    if (!res)
    {
        LOG("copyImage", UkrString("Не вдалося скопіювати фото з %1 до %2")
            .arg(path)
            .arg(newPhotoPath));
        return QString();
    }

    qDebug() << fii.fileName();
    return fii.fileName();
}

void Manager::printPacient()
{
    QPrintPreviewDialog previewDialog( &mPrinter );
    previewDialog.setWindowTitle(QString("QRDNK - Перегляд перед друком"));
    previewDialog.setWindowIcon(QIcon(QPixmap(":/print")));
    connect( &previewDialog, SIGNAL( paintRequested (QPrinter*) ),
             this, SLOT ( onPrintRequested(QPrinter*) ));
    previewDialog.exec();

}

void Manager::onPrintRequested(QPrinter *printer)
{
    printer->setResolution(200);
    printer->setCreator("QRDNK");
    printer->setDocName( pacient()->fullName() );
    printer->setPageSize(QPrinter::A4);
    printer->setOrientation(QPrinter::Portrait);
    printer->setPageMargins(20, 20, 10, 20, QPrinter::Millimeter);

    QString htmlContent = pacient()->genHtml();
    QTextDocument td;
    td.setHtml(htmlContent);
    td.print(printer);

    htmlContent.clear();
}

void Manager::clearCurrentFolder() const
{
    QDir cur( App->curTempDir() );
    if (!cur.entryList().isEmpty())
    {
        foreach (QString fPath, cur.entryList())
            cur.remove( fPath );
    }
}

void Manager::createPacient()
{
    if (mPacient!=NULL)
        delete App->pacient();

    mPacient = new Pacient();

    mMainWindow->setup();
}



void Manager::createInstance()
{
    if (mAppManager == 0)
    {
        mAppManager = new Manager();
        App->setup();
    }
}

void Manager::deleteInstance()
{
    if (mAppManager != 0)
    {
        mAppManager->saveSettings();
        delete mAppManager;
        mAppManager = 0;
    }
}

Manager* Manager::instance()
{
    return mAppManager;
}

